#!/usr/bin/python3
"""
Configure modprobe

The 'config' option allows the creation of a `.conf` configuration
file for modprobe in `/usr/lib/modprobe.d` with the name `filename`.

Currently supported "command" objects are:
  - for 'blacklist' command
    - 'command' property value: "blacklist"
    - 'modulename' property value: a non-empty string with the name of a module
  - for 'install' command
    - 'command' property value: "install"
    - 'modulename' property value: a non-empty string with the name of a module
    - 'cmdline' property value: a non-empty string representing the command to
      run instead of inserting the specified module.
"""


import os
import sys

import osbuild.api


SCHEMA = r"""
"additionalProperties": false,
"required": ["commands", "filename"],
"properties": {
  "filename": {
    "type": "string",
    "description": "Name of the modprobe configuration file.",
    "pattern": "^[\\w.-]{1,250}\\.conf$"
  },
  "commands": {
    "additionalProperties": false,
    "type": "array",
    "description": "Array of modprobe commands",
    "minLength": 1,
    "items": {
      "anyOf": [
        {
          "additionalProperties": false,
          "type": "object",
          "description": "'blacklist' command",
          "required": ["command", "modulename"],
          "properties": {
            "command": {
              "type": "string",
              "enum": ["blacklist"],
              "description": "modprobe command."
            },
            "modulename": {
              "type": "string",
              "minLength": 1,
              "description": "name of the module to blacklist."
            }
          }
        },
        {
          "additionalProperties": false,
          "type": "object",
          "description": "'install' command",
          "required": ["command", "modulename", "cmdline"],
          "properties": {
            "command": {
              "type": "string",
              "enum": ["install"],
              "description": "modprobe command."
            },
            "modulename": {
              "type": "string",
              "minLength": 1,
              "description": "name of the module to blacklis."
            },
            "cmdline": {
              "type": "string",
              "minLength": 1,
              "description": "command to run instead of inserting the specified module as normal."
            }
          }
        }
      ]
    }
  }
}
"""


def main(tree, options):
    config_file = options["filename"]

    config_dir = f"{tree}/usr/lib/modprobe.d"
    os.makedirs(config_dir, exist_ok=True)

    lines = []
    for config_command in options["commands"]:
        if config_command["command"] == "blacklist":
            lines.append(f'{config_command["command"]} {config_command["modulename"]}\n')
        elif config_command["command"] == "install":
            lines.append(f'{config_command["command"]} {config_command["modulename"]} {config_command["cmdline"]}\n')
        else:
            raise ValueError()

    with open(f"{config_dir}/{config_file}", "w") as f:
        f.writelines(lines)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
